<template>
  <div>
    <div class="playedu-main-top mb-24">
      <div class="d-flex">
        <PerButton
          type="primary"
          text="新建部门"
          class="mr-16"
          :icon="h(PlusOutlined)"
          p="department-cud"
          @click="setCreateVisible(true)"
        />
        <PerButton
          v-if="ldapEnabled"
          type="primary"
          text="LDAP同步"
          class="mr-16"
          :icon="h(PlusOutlined)"
          p="department"
          @click="setSyncModalVisible(true)"
        />
      </div>
    </div>

    <div class="playedu-main-body">
      <div v-if="loading" class="float-left text-center mt-30">
        <Spin />
      </div>

      <div
        class="playedu-tree"
        :style="{ display: loading ? 'none' : 'block', width: '366px' }"
      >
        <Tree
          v-if="treeData.length > 0"
          :tree-data="treeData"
          draggable
          block-node
          @select="onSelect"
          @dragenter="onDragEnter"
          @drop="onDrop"
          :switcher-icon="switcherIcon"
        >
          <template #title="{ dataRef }">
            <div class="tree-node">
              <span class="tree-node-text">{{ dataRef.name }}</span>
              <div v-if="!ldapEnabled" class="tree-node-actions">
                <Tooltip placement="top" title="可拖拽排序">
                  <i class="iconfont icon-icon-drag" />
                </Tooltip>
                <i
                  v-if="through('department-cud')"
                  class="iconfont icon-icon-edit"
                  @click="handleEdit(dataRef.key)"
                />
                <i
                  class="iconfont icon-icon-delete"
                  @click="handleDelete(dataRef.key, dataRef.name)"
                />
              </div>
            </div>
          </template>
        </Tree>
      </div>

      <DepartmentCreate
        :open="createVisible"
        @cancel="handleCreateCancel"
      />

      <DepartmentUpdate
        :id="did"
        :open="updateVisible"
        @cancel="handleUpdateCancel"
      />

      <!-- <LdapSyncModal
        :open="syncModalVisible"
        @cancel="handleSyncCancel"
      /> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, h, computed } from 'vue'
import { Tree, Spin, Modal, message, Tooltip } from 'ant-design-vue'
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons-vue'
import { useUserStore, useSystemStore } from '@/store'

import PerButton from '@/components/Common/permission-button.vue'
import DepartmentCreate from './create.vue'
import DepartmentUpdate from './update.vue'
// import LdapSyncModal from '@/components/Common/test111.vue'
import { department } from '@/api/index'

interface Option {
  key: string | number;
  name: string,
  children?: Option[];
}

interface DepartmentsBoxModel {
  [key: number]: Array<{ id: number; name: string }>;
}

const userStore = useUserStore()
const systemStore = useSystemStore()
const { confirm } = Modal

const loading = ref(true)
const refresh = ref(false)
const treeData = ref<Option[]>([])
const selectKey = ref<number[]>([])
const createVisible = ref(false)
const updateVisible = ref(false)
const syncModalVisible = ref(false)
const did = ref(0)

// 权限
const permissions = computed<Record<string, any>>(() => userStore.permissions || {})
// LDAP是否启用
const ldapEnabled = computed<boolean>(() => systemStore.getLdapEnabled ?? false)

onMounted(() => {
  getData()
})

watch(refresh, () => {
  getData()
})

const onSelect = (selectedKeys: any) => {
  selectKey.value = selectedKeys
}

const through = (p: string) => {
  return typeof permissions.value[p] !== 'undefined'
}

const getData = () => {
  loading.value = true
  department.departmentList({}).then((res: any) => {
    const departments: DepartmentsBoxModel = res.data.departments
    systemStore.saveDepartmentsAction(res.data.departments)
    if (JSON.stringify(departments) !== '{}') {
      treeData.value = buildTreeData(departments, 0)
    }
    loading.value = false
  })
}

const buildTreeData = (departments: DepartmentsBoxModel, id: number): Option[] => {
  const currentLevel = departments[id]
  if (!currentLevel) {
    return []
  }
  
  return currentLevel.map(item => ({
    key: item.id,
    name: item.name,
    children: departments[item.id] ? buildTreeData(departments, item.id) : undefined
  }))
}

const handleEdit = (id: number) => {
  did.value = id
  setUpdateVisible(true)
}

const handleDelete = (id: number, name: string) => {
  if (id === 0) return
  confirm({
    title: '操作确认',
    icon: h(ExclamationCircleFilled),
    content: `确认删除部门「${name}」吗？`,
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      department.destroyDepartment(id).then(() => {
        message.success('操作成功')
        refresh.value = !refresh.value
      })
    }
  })
}

const onDragEnter = (info: any) => {
  console.log(info)
}

const onDrop = (info: any) => {
  console.log('拖拽事件', info)
  // 这里可以和分类树一样，写排序提交逻辑
}

const setCreateVisible = (val: boolean) => {
  createVisible.value = val
}

const setUpdateVisible = (val: boolean) => {
  updateVisible.value = val
}

const setSyncModalVisible = (val: boolean) => {
  syncModalVisible.value = val
}

const handleCreateCancel = () => {
  setCreateVisible(false)
  refresh.value = !refresh.value
}

const handleUpdateCancel = () => {
  setUpdateVisible(false)
  refresh.value = !refresh.value
}


const switcherIcon = () => h('i', { class: 'iconfont icon-icon-fold c-gray' })
</script>

<style scoped>
.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-width: 0;
  padding: 4px 0;
}

.tree-node-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}
</style>
